import Taro, { Component } from '@tarojs/taro'
import { View, Text, Picker,Image ,Input ,Video,} from '@tarojs/components'
import './quicklyConsultation.css'
import { AtAvatar, AtImagePicker, AtList, AtListItem, AtInput, AtForm, AtButton, AtGrid,AtSearchBar,AtTag,AtTextarea } from "taro-ui"
import app from '../../main';
import reactMixin from 'react-mixin';
import myJs from './quicklyConsultationJs.js'

export default class QuicklyConsultation extends Component {

    config = {
        navigationBarTitleText: '快速咨询'
    }
    
    constructor () { 
        super(...arguments); 
        this.state = this.getData();
    };

    handleChange (event) {
        this.setState({
            value: event.target.value
        })
    }

    onChangeY () {
        
        this.setState({
            btnY:'color: #72d021; border: 1px solid #72d021; margin:5px 0 0 15px;',
            btnN:'color: #cccccc; border: 1px solid #cccccc; margin:5px 0 0 15px;',
            shifoujiuzhen:1,
            dateSel: '请选择日期',
            diseaseSel:'',
            hospitalSel:'请选择医院',
        })

    }
    
    onChangeN () {
        this.setState({
            btnY:'color: #cccccc; border: 1px solid #cccccc; margin:5px 0 0 15px;',
            btnN:'color: #72d021; border: 1px solid #72d021; margin:5px 0 0 15px;',
            dateSel: '',
            diseaseSel:'',
            hospitalSel:'',
            shifoujiuzhen:0
        })
        
    }

    onDateChange = e => {
        this.setState({
            dateSel: e.detail.value
        },()=>{
            console.log(this.state.dateSel)
        })
    }

    onDiseaseChange (value) {
        this.setState({
            diseaseSel:value
        })
    }

    onHospitalChange = e => {
        let me = this
        if(e.detail.column == 0){
            let citiarr = []
            let data = {province_id:me.state.proarrs[e.detail.value].id}
            app.get('web/hospital/cities', data, (res)=>{
                let list = res.data.result
                for(let i = 0; i < list.length; i++){
                    citiarr.push(list[i].name)
                }
                me.setState({
                    procolumn:e.detail.value,
                    citiarrs:list,
                    citiarrname:citiarr,
                    citicolumn:0,
                    hospitalcolumn:0
                },()=>{
                    let hospitalarr = []
                    let data = {province:me.state.proarrs[me.state.procolumn].name,city:me.state.citiarrs[me.state.citicolumn].name}
                    app.get('web/hospital/all', data, (res)=>{
                        let list = res.data.result
                        for(let i = 0; i < list.length; i++){
                            hospitalarr.push(list[i].name)
                        }
                        me.setState({
                            hospitalarrs:list,
                            hospitalname:hospitalarr,
                        },()=>{
                            me.setState({
                                hospitalSelector:[me.state.proarrname,me.state.citiarrname,me.state.hospitalname]
                            })
                        })
                    })
                })
            })
        }else if(e.detail.column == 1){
            let hospitalarr = []
            let data = {province:me.state.proarrs[me.state.procolumn].name,city:me.state.citiarrs[e.detail.value].name}
            app.get('web/hospital/all', data, (res)=>{
                let list = res.data.result
                for(let i = 0; i < list.length; i++){
                    hospitalarr.push(list[i].name)
                }
                me.setState({
                    citicolumn:e.detail.value,
                    hospitalarrs:list,
                    hospitalname:hospitalarr,
                    hospitalcolumn:0
                },()=>{
                    me.setState({
                        hospitalSelector:[me.state.proarrname,me.state.citiarrname,me.state.hospitalname]
                    })
                })
            })
        }else if(e.detail.column == 2){
            me.setState({
                hospitalcolumn:e.detail.value
            })
        }
    }

    change (e) {
        let index = e.detail.value[2] || 0
        this.setState({
            hospitalSel:this.state.hospitalname[index]
        })
    }

    //get 医院列表
    gethospital(){
        let me = this
        let data = {}
        let proarr = []
        let citiarr = []
        let hospitalarr = []
        app.get('web/hospital/provinces', data, (res)=>{
            let list = res.data.result
            for(let i = 0; i < list.length; i++){
                proarr.push(list[i].name)
            }
            app.get('web/hospital/cities',{province_id:list[0].id},(rps)=>{
                for (let j = 0; j < rps.data.result.length; j++) {
                    citiarr.push(rps.data.result[j].name)
                }
                app.get('web/hospital/all',{province:proarr[0],city:citiarr[0]},(rs)=>{
                    for (let l = 0; l < rs.data.result.length; l++) {
                        hospitalarr.push(rs.data.result[l].name)
                    }
                    me.setState({
                        proarrs:list,
                        proarrname:proarr,
                        citiarrs:rps.data.result,
                        citiarrname:citiarr,
                        hospitalarrs:rs.data.result,
                        hospitalname:hospitalarr
                    },()=>{
                        me.setState({
                            hospitalSelector:[me.state.proarrname,me.state.citiarrname,me.state.hospitalname]
                        })
                    })
                })
            })
        })
    }

    getSelectorData() {
        let me = this
        let proarr = [], cityarr = [], hospitalarr = []
        app.get('web/hospital/provinces', {}, (res)=>{
            for(let i = 0; i < res.data.result.length; i++){
                proarr.push(res.data.result[i].name)
                app.get('web/hospital/cities', {province_id:res.data.result[i].province_id}, (rps)=>{
                    for (let j = 0; j < rps.data.result.length; j++) {
                        cityarr.push(rps.data.result[j].name)
                    }
                    me.setState({
                        hospitalSelector:[proarr,cityarr,this.state.hospitalname],
                        proarrs:res.data.result
                    })
                })
            }
        })
    }

    componentWillMount(){
        if(!app.isEmptyObject(app.zixun)){
            console.log('zixun', app.zixun);
            this.setState({
                shifoujiuzhen:app.zixun.is_cure,
                dateSel:app.zixun.last_time,
                hospitalSel:app.zixun.cure_hospital,
                diseaseSel:app.zixun.cure_illness,
                value:app.zixun.main_suit,
                images: !app.isEmpty(app.zixun.images) ? app.zixun.images : []
            })
        }
        this.gethospital();
    }

    //跳转到如何拍照
    gotoHowToPhotograph(){
        app.zixun = {
            is_cure:this.state.shifoujiuzhen,
            last_time:this.state.dateSel,
            cure_hospital:this.state.hospitalSel,
            cure_illness:this.state.diseaseSel,
            main_suit:this.state.value,
            images: this.state.images
        }
        app.navigateTo('../howToPhotograph/howToPhotograph')
    }

    //跳转到如何拍视频
    gotoStep(){
        app.zixun = {
            is_cure:this.state.shifoujiuzhen,
            last_time:this.state.dateSel,
            cure_hospital:this.state.hospitalSel,
            cure_illness:this.state.diseaseSel,
            main_suit:this.state.value,
            images: this.state.images
        }
        app.navigateTo('../step/step')
    }

    //跳转到付款页面
    gotoPayment(){
        let me = this
        let images = me.state.images;
        let arrImg = [];
        for (let i=0;i<images.length;i++) {
            arrImg.push(images[i].url)
        }
        if(this.state.value == ''){
            Taro.showModal({
                title: '提示',
                content: '病情描述必须填写',
                showCancel:false
            })
            return;
        }
        if(this.state.shifoujiuzhen == 1){
            if(this.state.dateSel == '请选择日期' || this.state.dateSel == undefined || this.state.diseaseSel == '' || this.state.diseaseSel == undefined || this.state.hospitalSel == '请选择医院' || this.state.hospitalSel == undefined){
                Taro.showModal({
                    title:'提示',
                    content: '最后一次就诊时间、就诊的医院和确认的病情不能为空',
                    showCancel:false
                })
                return;
            }
        }
        let data = {
            is_cure:this.state.shifoujiuzhen,
            last_time:this.state.dateSel,
            cure_hospital:this.state.hospitalSel,
            cure_illness:this.state.diseaseSel,
            main_suit:this.state.value,
            eye_images:app.eyesphoto,
            eye_videoes:app.eyesvideo,
            illness_images:JSON.stringify(arrImg)
        }
        if (app.isEmpty(app.wz_order_id)) {
            app.post('web/myself/myInquiryAnswers', data, function(res){
                if(res.data.status == "success"){
                    me.clearFormData();
                    arrImg = ''
                    app.inquiry_answer_id = res.data.result.inquiry_answer_id
                    app.redirectTo('../Payment/Payment')
                }else{
                    Taro.showModal({
                        title: '提示',
                        content: '提交失败',
                        showCancel:false
                    })
                    return;
                }
            })
        } else {
            data.order_id = app.wz_order_id;
            app.post('web/myself/set_order_answer', data, function(res) {
                if(res.data.status == "success"){
                    me.clearFormData();
                    me.tiaoguo();
                }else{
                    Taro.showModal({
                        title: '提示',
                        content: '提交失败',
                        showCancel:false
                    })
                    return;
                }
            })
        }
    }

    tiaoguo() {
        var order_id = app.wz_order_id;
        var doctor_id = app.wz_doctor_id;
        app.wz_doctor_id = '';
        app.wz_order_id = '';
        app.redirectTo('../chatsub/pages/Chat/Chat?type=问诊订单&relate_id='+order_id+'&receiver_id='+doctor_id);
    }

    clearFormData() {
        app.eyesphoto = ''
        app.eyesvideo = ''
        app.zixun = {}
    }

    showImg (image) {
        app.prviewImage(image,[image])
    }

    changeImage(files, type, index) {
        if (type == 'add') {
            this.uploadImage(files);
        }
      
        if (type == 'remove') {
            var images = this.state.images;
            images.splice(index, 1);
            this.setState({
                images: images
            })  
        }    
    }

    uploadImage(files) {
        var me = this;
        me.setState({
            images: files
        })
        for (let i = 0; i < files.length; i++) {
            Taro.uploadFile({
                url: app.apiUri + '/admin/upload/image',
                filePath: files[i].url,
                name: 'file',
                formData: {
                    name: 'file'
                }
            }).then(function (res) {
                if (res.statusCode == 413) {
                    app.toast('文件过大，请重新上传');
                    let d = 0;
                    files.pop();
                    return;
                }
                var result = JSON.parse(res.data);
                var path = result.result;
                files[i].url = path;
                me.setState({
                    images: files
                });
            })
        }
    }

    uploadHeadImage() {
        var me = this;
        Taro.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                const tempFilePaths = res.tempFilePaths
                Taro.uploadFile({
                url: app.apiUri + '/admin/upload/image',
                filePath: tempFilePaths[0],
                name: 'file',
                formData: {
                    name: 'file'
                },
                success(res) {
                    let data = JSON.parse(res.data);
                    if (data.status == 200) {             
                        app.eyesfile = data.result;
                        me.setState({
                            eyesfile:data.result
                        })
                        // app.redirectTo('../quicklyConsultation/quicklyConsultation')
                    }
                }
                })
            }
        })
    }

    onFullScreenChange(e) {
        this.setState({
            fullScreen: e.detail.fullScreen
        })
    }

  render () {
    return (
      <View className='QuicklyConsultation'>
        <View className='emptyBox'/>
        <View className='color'>
            <View className='textBox'>
                <View style={this.state.style}>本次咨询的疾病是否去医院就诊过</View>
            </View>
            <View className='btnBox'>
                <AtButton customStyle={this.state.btnY} size='small' onClick={this.onChangeY.bind(this)}>是</AtButton>
                <AtButton customStyle={this.state.btnN} size='small' onClick={this.onChangeN.bind(this)}>否</AtButton>
            </View>
        </View>
        <View style={(this.state.btnY == 'color: #72d021; border: 1px solid #72d021; margin:5px 0 0 15px;') ? 'display:block;' : 'display:none;'}>
            <AtList >
                <Picker mode='date' onChange={this.onDateChange}>
                    <AtListItem extraText= {this.state.dateSel} arrow='right' title='最后一次就诊时间' />     
                </Picker>
                <Picker value={[this.state.procolumn,this.state.citicolumn,this.state.hospitalcolumn]} mode='multiSelector' range={this.state.hospitalSelector} onColumnChange={this.onHospitalChange.bind(this)} onChange={this.change.bind(this)}>
                    <AtListItem extraText= {this.state.hospitalSel} arrow='right' title='就诊的医院' />     
                </Picker>
                {/* <Picker mode='selector' range={this.state.diseaseSelector}  onChange={this.onDiseaseChange}>
                    <AtListItem extraText= {this.state.diseaseSel} arrow='right' title='确认疾病' />     
                </Picker> */}
            </AtList>
            <AtForm className='atinput'>
                <AtInput title='确认疾病'  placeholder='请填写疾病' value={this.state.diseaseSel} onChange={this.onDiseaseChange.bind(this)}></AtInput>
            </AtForm>
        </View>
        

        <View className='questBox'>
            <View className='iconI'>     
                <Image style={this.state.iconI} src={this.state.i}/>
            </View>
            <Text style={this.state.title}>病情描述</Text>
            <Text style='color:red; font-size: 16px; margin:0 0 0 10px;'>( 必须填写 )</Text>
            <View className='textareaBox' style={!this.state.fullScreen ? "display:block" : "display:none"}>
                <AtTextarea
                    value={this.state.value}
                    onChange={this.handleChange.bind(this)}
                    maxLength={500}
                    placeholder='请尽可能详细地描述您的病情症状,发病时间，曾经做过的检查，到院诊断的结果，用药情况，想要获得医生的什么帮助等;'
                />
            </View>           
        </View>

        <View className='questBox'>
            <View className='iconI'>     
                <Image style={this.state.iconI} src={this.state.i}/>
            </View>
            <Text style={this.state.title}>拍摄眼睛照片</Text>
            {/* <Text style='color:red; font-size: 16px; margin:0 0 0 10px;'>( 必须填写 )</Text> */}
            <View className='describe'>请严格根据操作指引拍摄双眼的照片</View>
            <View className='row'> 
                <View className='imgBox' style={app.eyesphoto == '' ? 'display:block; display: flex;justify-content:center;align-items:Center;' : 'display:none;'} onClick={this.gotoHowToPhotograph.bind(this)}>
                    <Image className='cameraIco' src={this.state.camera}/>
                </View>
                <View className='imgBox' style={app.eyesphoto == '' ? 'display:none' : 'display:block; '}>
                    <Image className='photo' src={app.eyesphoto} onClick={this.showImg.bind(this,app.eyesphoto)}/>
                </View>
                <View style={app.eyesphoto == '' ? 'display:none' : 'display:block; display: flex;justify-content:center;align-items:Center;'} className='imgBox' onClick={this.gotoHowToPhotograph.bind(this)}>
                    <Image className='cameraIco' src={this.state.camera}/>
                </View>
            </View>         
        </View>

        <View className='questBox'>
            <View className='iconI'>     
                <Image style={this.state.iconI} src={this.state.i}/>
            </View>
            <Text style={this.state.title}>拍摄眼睛视频</Text>
            {/* <Text style='color:red; font-size: 16px; margin:0 0 0 10px;'>( 必须填写 )</Text> */}
            <View className='describe'>请严格根据操作指引拍摄双眼的视频</View>
            <View className='row'> 
                <View className='imgBox' style={app.eyesvideo == '' ? 'display:block; display: flex;justify-content:center;align-items:Center;' : 'display:none'}onClick={this.gotoStep.bind(this)}>
                    <Image className='cameraIco' src={this.state.camera}/>
                </View>

                <View className='imgBox' style={app.eyesvideo == '' ? 'display:none' : 'display:block;'}>
                    <Video           
                        className='photo'
                        src={app.eyesvideo}
                        controls={true}
                        autoplay={false}
                        initialTime='0'
                        loop={false}
                        muted={false}
                        onFullScreenChange={this.onFullScreenChange}
                    />
                </View>
                
                <View style={app.eyesvideo == '' ? 'display:none' : 'display:block; display: flex;justify-content:center;align-items:Center;'} className='imgBox' onClick={this.gotoStep.bind(this)}>
                    <Image className='cameraIco' src={this.state.camera}/>
                </View>
            </View> 
        </View>

        <View className='questBox'>
            <View className='iconI'>     
                <Image style={this.state.iconI} src={this.state.i}/>
            </View>
            <Text style={this.state.title}>上传资料，病例等</Text>
            <View className='describe'>上传化验单，检查片子，报告单，药品方等资料会有利于医生为您给出更加全面的建议</View>
               <View className='imagepicker'>
                   <AtImagePicker 
                         multiple={false}
                         count={1}
                         files={this.state.images}
                         onChange={this.changeImage.bind(this)}
                    ></AtImagePicker>
               </View>
            {/*<View className='imgBox' style={app.eyesfile == '' ? 'display:none; display: flex;justify-content:center;align-items:Center;' : 'display:none'} onClick={this.uploadHeadImage.bind(this)}>
                <Image className='cameraIco' src={this.state.camera}/>
            </View>
            <View className='imgBox' style={app.eyesfile == '' ? 'display:none' : 'display:block;'}>
                <Image className='photo' src={this.state.eyesfile} />
            </View>
            <View style={app.eyesfile == '' ? 'display:none' : 'display:block; display: flex;justify-content:center;align-items:Center;'} className='imgBox' onClick={this.uploadHeadImage.bind(this)}>
                <Image className='cameraIco' src={this.state.camera}/>
            </View>*/}
        </View>

        <View className='blank'></View>

        <View className='bottom'>
            {
                !app.wz_order_id ?
                (
                    <View className='btnBox2'>
                        <AtButton type='primary' onClick={this.gotoPayment.bind(this)}>下一步</AtButton>
                    </View>  
                ) : 
                (
                    <View className='btnBox2'>
                        <AtButton type='secondary'className='leftbtn' onClick={this.tiaoguo.bind(this)}>跳过</AtButton>
                        <AtButton type='primary' className='rightbtn' onClick={this.gotoPayment.bind(this)}>提交</AtButton>
                    </View>  
                )
            }
        </View>
      </View>
    )
  }
}
reactMixin.onClass(QuicklyConsultation,myJs);
